<template>
  <div class="main">
    <div class="part">
      <div class="p-title">
        <div class="title">
          <span>短信群发</span>
          <MyToolTip
            content="本系统为用户提供的基于短信模板的短信群发功能，能够将将指定信息快速发送至国内手机号码。\n该功能具有如下特点：\n快速稳定：国内短信秒级可达，99%到达率，与工信部携号转网平台实时互联。\n使用便捷：批量上传时后几号，群发简单便捷。\n智能监控调度：电信级运维保障，实时监控、自动切换，确保发送成功率。\n高并发：高效的调度算法解决高峰时段的业务压力。"
          />
        </div>
      </div>
      <div class="p-cont">
        <div class="opr">
          <div class="opr-left">
            <el-button type="primary" @click="createNewDist"
              >新建群发</el-button
            >
          </div>
        </div>
        <div class="table-wrap">
          <el-table :data="distList" style="width: 100%" stripe>
            <el-table-column label="任务名称" prop="taskName" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                {{ scope.row.status === 1 ? "待发送" : "已发送" }}
              </template>
            </el-table-column>
            <el-table-column prop="createDate" label="发送时间" />
            <el-table-column fixed="right" label="操作" width="200">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="checkDist(scope.row)"
                  >查看</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="del-btn">
          <!-- <div class="del-left">
            <el-button type="primary" @click="plDeleteDrugs"
              >批量删除</el-button
            >
          </div> -->
          <div class="del-right">
            <myPagination
              :total="listNum || 0"
              @currentChange="currentChange"
              ref="myPaginationRef"
            />
          </div>
        </div>
        <!-- <div class="page">
          <div class="page-left">共{{ listNum }}条数据</div>
        </div> -->
      </div>

      <el-dialog v-model="dialogVisible" title="新建/编辑短信群发">
        <div class="dialog-cont" style="display: flex; align-items: flex-start">
          <div class="dialog-adddrug">
            <el-form
              :model="form"
              label-width="120px"
              ref="ruleFormRef"
              :rules="rules"
            >
              <el-form-item prop="taskName">
                <template #label
                  >任务名称
                  <MyToolTip
                    color="#606266"
                    content="任务名称主要用于记录本次群发短信的内容摘要，接收短信的用户不会看见此名称，任务名称不超过50个汉字。"
                  />
                </template>
                <el-input
                  v-model="form.taskName"
                  placeholder="请输入任务名称"
                  :disabled="editType === 'check'"
                />
              </el-form-item>
              <el-form-item prop="signName">
                <template #label
                  >短信签名
                  <MyToolTip
                    color="#606266"
                    content="代表短信发送方。如没有合适的签名，请联系我们。"
                  />
                </template>
                <el-select
                  v-model="form.signName"
                  placeholder="请选择短信签名"
                  :disabled="editType === 'check'"
                  @change="signTempChange"
                >
                  <el-option
                    v-for="(sign, index) in signList"
                    :key="index"
                    :label="sign"
                    :value="sign"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="templateCode">
                <template #label
                  >短信模板
                  <MyToolTip
                    color="#606266"
                    content="主要用于记录短信内容的模板，选择模板后可在右侧预览短信发送样式。如没有合适的模板，请联系我们。"
                  />
                </template>
                <el-select
                  v-model="form.templateCode"
                  placeholder="请选择短信模板"
                  :disabled="editType === 'check'"
                  @change="signTempChange"
                >
                  <el-option
                    v-for="(tempObj, index) in templateList"
                    :key="index"
                    :label="tempObj.templateName"
                    :value="tempObj.templateCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                :disabled="userConfig.smsMargin <= 0"
                v-if="editType === 'new'"
              >
                <template #label
                  ><label
                    ><span style="color: #f56c6c; margin-right: 4px">*</span
                    >接收号码</label
                  >
                  <MyToolTip
                    color="#606266"
                    content="平台通过上传号码列表文件的方式获得接收短信的手机号码：\n1、点击“下载模板”， 下载excel模板文件\n2、根据下载的文件要求填入手机号和相应的内容\n3、点击“导入文件”，选择刚才编辑好的excel文件导入到系统\n4、系统将根据文件预估本次短信的待发送量，如果您的短信余量不够，请联系我们\n5、短信长度（字数）＝短信签名字数+短信模板内容字数。其中，短信模板字数上限为500字。短信长度不超过70个字，按照一条短信计费；超过70个字，即为长短信，按照67字/条拆分成多条计费。\n示例：短信长度为160个字，按照67字、67字、26字分隔成三条短信进行计费"
                  />
                </template>
                <template #default>
                  <div>
                    <a
                      href="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/saas/%E5%8F%91%E9%80%81%E7%9F%AD%E4%BF%A1%E6%A8%A1%E6%9D%BF.xlsx"
                      download
                      style="color: rgb(64, 158, 255); cursor: pointer"
                      >下载模板</a
                    >,填写号码等相应内容，点下面按钮导入编辑好的文件
                  </div>

                  <el-upload
                    ref="uploadRef"
                    v-model:file-list="uploadFileList"
                    class="upload-demo"
                    :action="actionUrl"
                    :headers="uploadHeaders"
                    :show-file-list="true"
                    :limit="1"
                    :auto-upload="false"
                    :on-change="uploadFileChange"
                    :on-remove="removeFile"
                    :on-exceed="exceedFile"
                    accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  >
                    <el-button
                      type="primary"
                      :disabled="userConfig.smsMargin <= 0"
                      >导入文件</el-button
                    >
                  </el-upload>
                  <div
                    class="remain-num"
                    style="width: 100%; margin-top: -10px"
                  >
                    短信余量：{{ userConfig.smsMargin
                    }}<span v-if="uploadDataList.length > 0"
                      >，本次待发量：{{ uploadDataList.length }}</span
                    >
                  </div>
                </template>
              </el-form-item>
              <el-form-item v-else>
                <template #label
                  ><label
                    ><span style="color: #f56c6c; margin-right: 4px">*</span
                    >接收号码</label
                  >
                  <MyToolTip
                    color="#606266"
                    content="平台通过上传号码列表文件的方式获得接收短信的手机号码：\n1、点击“下载模板”， 下载excel模板文件\n2、根据下载的文件要求填入手机号和相应的内容\n3、点击“导入文件”，选择刚才编辑好的excel文件导入到系统\n4、系统将根据文件预估本次短信的待发送量，如果您的短信余量不够，请联系我们\n5、短信长度（字数）＝短信签名字数+短信模板内容字数。其中，短信模板字数上限为500字。短信长度不超过70个字，按照一条短信计费；超过70个字，即为长短信，按照67字/条拆分成多条计费。\n示例：短信长度为160个字，按照67字、67字、26字分隔成三条短信进行计费"
                  />
                </template>
                <template #default>
                  <a
                    :href="form.fileAddress"
                    download
                    style="color: rgb(64, 158, 255); cursor: pointer"
                    >{{ form.fileAddress }}</a
                  >
                </template>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm"
                  :disabled="editType === 'check'"
                  >提交</el-button
                >
                <el-button @click="resetSubmit" v-if="editType === 'new'"
                  >重置表单</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="device iphone-x">
            <!--    外部轮廓    -->
            <div class="frame">
              <div class="content">
                <!-- <div class="time">10:19</div> -->

                <div class="sms" v-if="smsContent">
                  {{ smsContent }}
                </div>
              </div>
            </div>

            <!--    天线    -->
            <div class="stripe" />

            <!--    听筒孔    -->
            <div class="header">
              <div class="sensors" />
            </div>

            <!--    按键    -->
            <div class="btns" />
            <div class="power" />
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, onBeforeMount } from "vue";

import myPagination from "@/components/myPagination.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, genFileId } from "element-plus";
import {
  getSmsTasks,
  getSmsTaskDetail,
  createSmsTask,
  getSmsTemplateList
} from "@/api/publicity";
import { getUserConfiguration } from "@/api/system";
import MyToolTip from "@/components/myToolTip.vue";
import { getToken, formatToken } from "@/utils/auth";
import { whReqBaseUrl as VITE_REQUEST_BASE_SAAS_API } from "@/api/common";
import * as XLSX from "xlsx/xlsx.mjs";
// import XLSX from "xlsx/xlsx.mjs";
// const XLSX = window.XLSX;
const actionUrl = ref(
  `${VITE_REQUEST_BASE_SAAS_API}/contentManagements/uploadFile`
);
// 请求头部
const data = getToken();
const uploadHeaders = {
  Authorization: formatToken(data.accessToken)
};

const editType = ref<"new" | "check" | "edit">("new");

const userStore = useUserStoreHook();
const listNum = ref(0);
const myPaginationRef = ref();
const distList = ref([]);
const dialogVisible = ref(false);
const ruleFormRef = ref();
const signList = ref([]);
const templateList = ref([]);
const form = ref({
  taskName: "",
  signName: "",
  templateCode: "",
  fileAddress: "" //健康教育目标人
});
const userConfig = ref({ smsMargin: 0, signs: "" });

const uploadDataList = ref([]);
const uploadFileList = ref([]);
const uploadRef = ref(null);
const smsContent = ref("");
const rules: any = reactive({
  taskName: [
    {
      required: true,
      message: "任务名称不能为空，且不超过50个字符",
      max: 50,
      trigger: "blur"
    }
  ],
  signName: [
    { required: true, message: "短信签名不能为空", trigger: "change" }
  ],
  templateCode: [
    { required: true, message: "短信模板不能为空", trigger: "change" }
  ]
});

function signTempChange() {
  if (form.value.signName && form.value.templateCode) {
    const curTemplate = templateList.value.find(item => {
      return item.templateCode === form.value.templateCode;
    });
    smsContent.value =
      "【" + form.value.signName + "】" + curTemplate.templateContent;
  }
}

function currentChange() {
  getSmsApi();
}

async function uploadFileChange(uploadFile) {
  const data = await uploadFile.raw.arrayBuffer();
  const workbook = (XLSX as any).read(data);
  const sheetName = workbook.SheetNames[0];
  uploadDataList.value = (XLSX as any).utils.sheet_to_json(
    workbook.Sheets[sheetName]
  );
  console.log("uploadDataList.value:", uploadDataList.value);
}
function removeFile() {
  uploadDataList.value = [];
}

function exceedFile(files) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
}

function createNewDist() {
  editType.value = "new";
  dialogVisible.value = true;
  smsContent.value = "";
  resetSubmit();
}
async function checkDist(row) {
  const detail = await getSmsTaskDetail(row.id);
  form.value = detail;
  dialogVisible.value = true;
  editType.value = "check";
}

async function getSmsApi() {
  const listRes = await getSmsTasks({
    skip:
      (myPaginationRef.value.currentPage - 1) *
      myPaginationRef.value.curPageSize,
    limit: myPaginationRef.value.curPageSize
  });
  distList.value = listRes.list;
  if (myPaginationRef.value.currentPage === 1) {
    listNum.value = listRes.total;
  }
}
async function getUserConfigurationData() {
  const res = await getUserConfiguration(userStore.userInfo.user);
  if (res) {
    console.log("res:", res);
    userConfig.value = res;

    signList.value = userConfig.value.signs.split(",");
  }
}
function submitForm() {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        if (!uploadFileList.value.length) {
          ElMessage({
            type: "error",
            message: "接收号码不能为空"
          });
          return;
        }
        // 检查模板是否符合规范
        const noValidPhoneList = uploadDataList.value
          .filter(item => {
            return !/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
              item["手机号"]
            );
          })
          .map(item => {
            return item["手机号"];
          });
        if (noValidPhoneList.length > 0) {
          ElMessage({
            type: "error",
            message:
              "以下手机号有问题，请检查后重新上传：" +
              noValidPhoneList.join(",")
          });
          return;
        }
        // 检查短信数是否超标
        const curTemplate = templateList.value.find(item => {
          return item.templateCode === form.value.templateCode;
        });

        // console.log("curTemplate:", curTemplate);

        // 一个模板可以发送的短信数
        const templateSmsNum = Math.ceil(
          curTemplate.templateContent.length / 64
        );
        if (templateSmsNum > userConfig.value.smsMargin) {
          ElMessage({
            type: "error",
            message: `当前短信模板需要发送${templateSmsNum}条短信，当前发送的总短信数量将超过您剩余的短信额度，请修改后重新提交。`
          });
          return;
        }

        const tempForm = Object.assign({}, form.value);

        delete tempForm.fileAddress;
        const tip = editType.value === "new" ? "新增" : "编辑";
        // console.log("uploadFileList.value:", uploadFileList.value);
        try {
          const res = await createSmsTask({
            userId: userStore.userInfo.user,
            data: JSON.stringify(tempForm),
            file: uploadFileList.value[0].raw
          });
          if (!res || res.code === 0) {
            ElMessage({
              message: tip + "成功",
              type: "success"
            });
            resetSubmit();
          }
          dialogVisible.value = false;
          getSmsApi();
        } catch (error) {
          ElMessage({
            message: tip + "失败," + JSON.stringify(error),
            type: "error"
          });
        }
      }
    });
  }
}

function resetSubmit() {
  form.value = {
    taskName: "",
    signName: "",
    templateCode: "",
    fileAddress: "" //健康教育目标人数
  };
  uploadFileList.value = [];
  ruleFormRef.value?.clearValidate();
}
onBeforeMount(async () => {
  // 获取短信模板
  templateList.value = await getSmsTemplateList();
  // 获取当前用户短信签名
  await getUserConfigurationData();
  // 获取群发短信列表
  await getSmsApi();
});
onMounted(async () => {});
</script>
<style scoped lang="scss">
::v-deep(.el-backtop) {
  display: none !important;
}

::v-deep(.el-form-item__label) {
  align-items: center !important;
}

.main {
  .part {
    .p-title {
      justify-content: flex-start;
    }
  }
}

.opr {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .opr-right {
    width: 300px;
  }
}

.table-wrap {
  margin-top: 20px;
}

.del-btn {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .page-left {
    color: #bbb;
  }
}

.dialog-adddrug {
  width: 400px;

  .dist-row {
    display: flex;
    align-items: center;

    .dist-btn {
      margin: 0px 10px 10px 0px;
    }
  }
}

.device {
  margin: 50px auto;
  margin-top: 0px;
  position: relative;

  &::before,
  &::after {
    box-sizing: border-box;
    display: block;
  }

  .frame {
    z-index: 1;
  }
}

.iphone-x {
  height: 694px;
  width: 342px;
  zoom: 0.7;
}

.iphone-x .frame {
  background: #222;
  border-radius: 54px;
  box-shadow: inset 0 0 0 2px #606467, inset 0 0 0 6px #e2e3e4;
  height: 694px;
  padding: 22px;
  width: 342px;
}

.iphone-x .content {
  background-color: #fff;
  background-position: center center;
  background-size: cover;
  border-radius: 32px;
  height: 650px;
  position: relative;
  width: 300px;
  padding-top: 20px;
  box-sizing: border-box;
}

.iphone-x .stripe::after,
.iphone-x .stripe::before {
  border: solid rgba(51, 51, 51, 0.25);
  border-width: 0 6px;
  content: "";
  height: 5px;
  left: 0;
  position: absolute;
  width: 100%;
  z-index: 9;
}

.iphone-x .stripe::after {
  top: 68px;
}

.iphone-x .stripe::before {
  bottom: 68px;
}

.iphone-x .header {
  background: #222;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 16px;
  height: 24px;
  left: 50%;
  margin-left: -82px;
  position: absolute;
  top: 22px;
  width: 164px;
  z-index: 199;
}

.iphone-x .header::after,
.iphone-x .header::before {
  content: "";
  height: 6px;
  position: absolute;
  top: 0;
  width: 6px;
}

.iphone-x .header::after {
  background: radial-gradient(
    circle at bottom left,
    transparent 0,
    transparent 75%,
    #222 75%,
    #222 100%
  );
  left: -6px;
}

.iphone-x .header::before {
  background: radial-gradient(
    circle at bottom right,
    transparent 0,
    transparent 75%,
    #222 75%,
    #222 100%
  );
  right: -6px;
}

.iphone-x .sensors::after,
.iphone-x .sensors::before {
  content: "";
  position: absolute;
}

.iphone-x .sensors::after {
  background: #444;
  border-radius: 2.5px;
  height: 5px;
  left: 50%;
  margin-left: -20px;
  top: 4px;
  width: 40px;
}

.iphone-x .sensors::before {
  background: #444;
  border-radius: 50%;
  height: 11px;
  left: 50%;
  margin-left: 30px;
  top: 1px;
  width: 11px;
}

.iphone-x .btns {
  background: #606467;
  height: 26px;
  left: -2px;
  position: absolute;
  top: 92px;
  width: 3px;
}

.iphone-x .btns::after,
.iphone-x .btns::before {
  background: #606467;
  content: "";
  height: 50px;
  left: 0;
  position: absolute;
  width: 3px;
}

.iphone-x .btns::after {
  top: 48px;
}

.iphone-x .btns::before {
  top: 112px;
}

.iphone-x .power {
  background: #606467;
  height: 80px;
  position: absolute;
  right: -2px;
  top: 160px;
  width: 3px;
}

.iphone-x .time {
  margin-left: 22px;
  margin-top: 10px;
}

.iphone-x .sms {
  width: 85%;
  margin: auto;
  margin-top: 30px;
  padding: 10px;
  background: rgb(231, 231, 231);
  color: rgb(30, 30, 30);
  font-size: 20px;
  position: relative;
  border-radius: 10px;
  word-break: break-all;
}

.iphone-x .sms::before {
  display: none;
  content: " ";
  left: -20px;
  bottom: 0px;
  position: absolute;
  width: 0px;
  height: 0px;
  border-top: 16px solid transparent;
  border-right: 16px solid rgb(231, 231, 231);
  border-bottom: 16px solid transparent;
}

.el-select {
  width: 100%;
}
</style>
